using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bumblebee;
using System.Threading;
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Bumblebee.Configuration;

namespace BeetlexDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
            {
                services.AddHostedService<HttpServerHosted>();
            });
            //.ConfigureWebHostDefaults(webBuilder =>
            //{
            //    webBuilder.UseStartup<Startup>();
            //});
    }

    public class HttpServerHosted : IHostedService
    {
        private Gateway g;

        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            g = new Gateway();
            g.HttpOptions(o =>
            {
                o.LogToConsole = true;
                o.WriteLog = true;
                o.SSL = true;
                o.SSLPort = 443;
                o.SslProtocols = System.Security.Authentication.SslProtocols.Tls;
            });
            g.Open();
            g.LoadPlugin(
                typeof(Bumblebee.Configuration.Management).Assembly, typeof(Bumblebee.Jwt.JwtPlugin).Assembly,
                typeof(Bumblebee.Aggregation.RequestAggregatePlugin).Assembly,
                typeof(Bumblebee.ConcurrentLimits.IPConcurrentLimits).Assembly,
                typeof(Bumblebee.InvalidUrlFilter.RequestUrlFilter).Assembly, typeof(Bumblebee.UrlRewrite.RewriteLoader).Assembly);
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                var ps = new ProcessStartInfo($"https://localhost/__system/bumblebee/index.html")
                {
                    UseShellExecute = true,
                    Verb = "open"
                };
                Process.Start(ps);
            }
            return Task.CompletedTask;
        }
        public virtual Task StopAsync(CancellationToken cancellationToken)
        {
            g.Dispose();
            return Task.CompletedTask;
        }
    }
}
